<template>
  <div class="zoomable-image-container" ref="containerRef">
    <img :src="imageUrl" :alt="altText" :style="imageStyle" @click="handleImageClick" />

    <!-- 渐隐遮罩 -->
    <div class="fade-overlay"></div>

    <!-- 交互区域 -->
    <svg class="interactive-areas-svg" ref="svgRef">
      <polygon
        v-for="(area, index) in interactiveAreas"
        :key="index"
        :points="getPolygonPoints(area)"
        :class="['interactive-area', { hovered: area.hovered }]"
        @mouseenter="handleAreaEnter(index)"
        @mouseleave="handleAreaLeave(index)"
        @click="handleAreaClick(area)"
      />
    </svg>

    <!-- 弹窗 -->
    <div v-if="showPopup" class="popup" :style="popupStyle">
      <div class="popup-content">
        <h3>{{ currentArea?.title }}</h3>
        <p>{{ currentArea?.description }}</p>
        <div class="popup-buttons">
          <button @click="closePopup" class="close-btn">关闭</button>
          <button @click="viewDetails" class="detail-btn">查看详情</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, reactive } from "vue"

// 定义区域类型
interface InteractiveArea {
  id: string
  title: string
  description: string
  points: { x: number; y: number }[] // 多边形顶点坐标
  hovered?: boolean
}

const props = withDefaults(
  defineProps<{
    imageUrl: string
    altText?: string
    initialScale?: number
    minScale?: number
    maxScale?: number
    interactiveAreas?: InteractiveArea[]
    debugMode?: boolean
  }>(),
  {
    altText: "",
    initialScale: 1,
    minScale: 0.1,
    maxScale: 5,
    interactiveAreas: () => [],
    debugMode: false
  }
)

const emit = defineEmits<{
  "view-details": [area: InteractiveArea]
}>()

const containerRef = ref<HTMLDivElement | null>(null)
const svgRef = ref<SVGSVGElement | null>(null)
const scale = ref(props.initialScale)
const isDragging = ref(false)
const translateX = ref(0)
const translateY = ref(0)

// 弹窗相关
const showPopup = ref(false)
const currentArea = ref<InteractiveArea | null>(null)
const popupStyle = reactive({
  top: "0px",
  left: "0px"
})

const imageStyle = computed(() => ({
  transform: `scale(${scale.value}) translate(${translateX.value}px, ${translateY.value}px)`,
  transition: isDragging.value ? "none" : "transform 0.2s ease"
}))

const handleImageClick = (event: MouseEvent) => {
  if (!props.debugMode) {
    return
  }

  const container = containerRef.value
  if (!container) { return }

  // 获取容器的边界矩形
  const rect = container.getBoundingClientRect()

  // 计算点击位置相对于容器的坐标
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top

  // 输出点击位置
  console.log(`{ x: ${x}, y: ${y} },`)
}

// 获取多边形顶点字符串，并应用偏移量
const getPolygonPoints = (area: InteractiveArea) => {
  return area.points.map(point => `${point.x},${point.y}`).join(" ")
}

// 处理区域鼠标进入
const handleAreaEnter = (index: number) => {
  const areas = [...props.interactiveAreas]
  areas[index].hovered = true
}

// 处理区域鼠标离开
const handleAreaLeave = (index: number) => {
  const areas = [...props.interactiveAreas]
  areas[index].hovered = false
}

// 处理区域点击
const handleAreaClick = (area: InteractiveArea) => {
  currentArea.value = area
  showPopup.value = true

  // 设置弹窗位置（可以根据需要调整）
  popupStyle.top = "50px"
  popupStyle.left = "50px"
}

// 关闭弹窗
const closePopup = () => {
  showPopup.value = false
  currentArea.value = null
}

// 查看详情
const viewDetails = () => {
  if (currentArea.value) {
    emit("view-details", currentArea.value)
    closePopup()
  }
}

// 添加键盘事件支持缩放
const handleKeyDown = (e: KeyboardEvent) => {
  if (e.key === "+" || e.key === "=") {
    scale.value = Math.min(props.maxScale, scale.value + 0.1)
  } else if (e.key === "-" || e.key === "_") {
    scale.value = Math.max(props.minScale, scale.value - 0.1)
  } else if (e.key === "0") {
    // 重置缩放
    scale.value = props.initialScale
    translateX.value = 0
    translateY.value = 0
  }
}

onMounted(() => {
  window.addEventListener("keydown", handleKeyDown)
})

onUnmounted(() => {
  window.removeEventListener("keydown", handleKeyDown)
})
</script>

<style scoped lang="scss">
.zoomable-image-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;

  img {
    max-width: none;
    max-height: none;
    transform-origin: center center;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .fade-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    pointer-events: none;
    background: radial-gradient(ellipse at center, rgba(0, 0, 0, 0) 40%, rgba(0, 0, 0, 0.8) 90%, rgba(0, 0, 0, 1) 100%);
    z-index: 10;
  }

  .interactive-areas-svg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 20;
  }

  .interactive-area {
    pointer-events: auto;
    cursor: pointer;
    transition: all 0.3s ease;

    &.hovered {
      fill: rgba(255, 255, 0, 0.3);
      stroke: yellow;
      stroke-width: 2;
    }

    &:not(.hovered) {
      fill: transparent;
      stroke: none;
    }
  }

  .popup {
    position: absolute;
    z-index: 100;
    background: rgba(0, 0, 0, 0.9);
    color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    min-width: 300px;

    .popup-content {
      h3 {
        margin-top: 0;
        margin-bottom: 10px;
        font-size: 18px;
        color: #fff;
      }

      p {
        margin-bottom: 15px;
        line-height: 1.5;
        color: #ddd;
      }

      .popup-buttons {
        display: flex;
        gap: 10px;
        justify-content: flex-end;

        button {
          padding: 8px 16px;
          border: none;
          border-radius: 4px;
          cursor: pointer;
          font-size: 14px;
          transition: all 0.3s ease;

          &.close-btn {
            background: #6c757d;
            color: white;

            &:hover {
              background: #5a6268;
            }
          }

          &.detail-btn {
            background: #007bff;
            color: white;

            &:hover {
              background: #0056b3;
            }
          }
        }
      }
    }
  }
}
</style>
